<?php
namespace app\common\controller;

/**
 * 学习试卷类
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/09/27
 * Time: 10:24
 */
class ClassLearnPaper{

    /**
     * 生成试卷
     * @param $openid
     * @param $clid
     * @param $ckid
     * @param $ti_num
     * @param $clcid
     * @param $ku_use
     * @return array
     */
    public function gen_paper($openid,$clid,$ckid,$ti_num,$clcid,$ku_use){
        $kuid_arr = json_decode($ckid,true);

        //题的总数
        $ti_total_num = array_sum($kuid_arr);

        //算出每个题库，出题数量
        $per_ku_ti_num = [];
        foreach($kuid_arr as $k => $v) {
            $per_ku_ti_num[$k] = round(($v / $ti_total_num) * $ti_num);
        }

        $ctid_arr = [];
        foreach ($ku_use as $k_1 => $v_1) {
            if(!empty($v_1)){
                //如果可用题库的数量小于每次取的数量，就取数组的长度
                $num = count($v_1) < $per_ku_ti_num[$k_1] ? count($v_1) : $per_ku_ti_num[$k_1];

                //如果权重算出来为0，就不出这个库的题
                if($num > 0){
                    //从每个库里，随机出题，出题数量为$num
                    $ti_keys = array_rand($v_1,$num);
                    if(is_int($ti_keys)){
                        $tmp = $ti_keys;
                        $ti_keys = [];
                        $ti_keys[0] = $tmp;
                    }

                    foreach($ti_keys as $k_2 => $v_2) {
                        $ctid = $v_1[$v_2];
                        array_push($ctid_arr,$ctid);
                    }
                }
            }
        }

        //获取所有题目（题目数组）
        $paper = [];
        foreach ($ctid_arr as $k => $v){
            $paper[$k]['openid'] = $openid;
            $paper[$k]['clid'] = $clid;
            $paper[$k]['clcid'] = $clcid;
            $paper[$k]['ctid'] = $v;
        }

        return $paper;
    }
}